﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Data.OleDb;
using Aandelendelen.Mail;
using Aandelendelen.Obs;
using Aandelendelen.Db;

namespace Aandelendelen.Daily
{
	public class InactiveMembers : DailyJob
	{
		int[] inactivePeriodsInDays = new int[4] { 366, 397, 421, 428 };

		public InactiveMembers(XmlNode jobNode)
			: base(jobNode, "Mailing inactive members...")
		{ }

		public override void Execute()
		{
			this.OnStart();

			try
			{
				this.SendInactiveMessages();
			}
			catch (Exception e)
			{
				this.OnError(e);
			}

			this.OnEnd();
		}

		private void SendInactiveMessages()
		{
			for (int i = 0; i < 4; i++)
			{
				this.SendInactiveMessage(i);
			}
		}

		private void SendInactiveMessage(int sequence)
		{
			int daysInactive = this.inactivePeriodsInDays[sequence];

			DateTime reminderDate = DateTime.Today.AddDays(-daysInactive);

			QueryArguments args = new QueryArguments();

			args.Add("date1", reminderDate, OleDbType.Date);
			args.Add("date2", reminderDate.AddDays(1), OleDbType.Date);
			args.Add("date3", reminderDate, OleDbType.Date);
			args.Add("date4", reminderDate.AddDays(1), OleDbType.Date);

			Query query = new Query("s_inactive", args);

			ResultSet resultSet = (ResultSet)query.Execute();

			for (int i = 0; i < resultSet.Count; i++)
			{
				EMail mail = this.SendMail(sequence, resultSet, i);

				if (mail != null)
					emails.Add(mail);

				if (sequence == 3)
				{
					CommonQueries.CancelAccount((int)resultSet[i, "Id"], queries);
				}
			}
		}

		private EMail SendMail(int sequence, ResultSet resultSet, int row)
		{
			Userinfo userInfo = new Userinfo(resultSet, row, false);

			MailArguments mailArgs = MailArguments.MailArgs;
			mailArgs.Clear();

			mailArgs["{aanhef}"] = userInfo.MailAanhef;
			mailArgs["{saldo}"] = ObjectFormatter.GetCurrencyString(userInfo.Saldo);

			string mailTag = null;

			switch (sequence)
			{
				case 0: mailTag = "firstinactivereminder";
					break;
				case 1: mailTag = "secondinactivereminder";
					break;
				case 2: mailTag = "thirdinactivereminder";
					break;
				case 3: mailTag = "removed";
					break;
			}

			if (mailTag == null)
				return null;

			EMail mail = MailCache.GetMail(mailTag);
			mail.Recipients = userInfo.Email;

			return mail;
		}
	}
}